package com.wanshi.service;

import com.wanshi.dao.UserDao;
import com.wanshi.entity.User;
import com.wanshi.exception.UserException;
import com.wanshi.utils.EmailUtil;
import com.wanshi.utils.JDBCUtil;
import org.apache.commons.dbutils.DbUtils;

import java.sql.Connection;
import java.util.UUID;

public class UserService {

    private UserDao userDao = new UserDao();

    public User findUserByName(String username) {
       return userDao.findUserByName(username);
    }

    public void addUser(User user) {
        //userDao.addUser(user);
        Connection connection = null;
        try{
            connection = JDBCUtil.getConn();
            connection.setAutoCommit(false);

            //1 插入数据库
            String statecode = UUID.randomUUID().toString().replace("-","");
            user.setStatecode(statecode);
            user.setState(0);
            userDao.addUser(connection,user);
            //2 发邮件
            String body = "请点击链接激活用户,如果不能点击把地址复制到浏览器中打开," +
                    "http://192.168.116.253/jingdong/active?statecode="+user.getStatecode();

            EmailUtil.sendEmail("181186368@qq.com","wkrdewoixlztbjea",
                    user.getEmail(),"我的京东激活邮件",body);

            DbUtils.commitAndCloseQuietly(connection);
        }catch (Exception e){
            e.printStackTrace();
            DbUtils.rollbackAndCloseQuietly(connection);
        }
    }

    public void updateUserByCode(String statecode) {
        //1 重复激活

        //2  超时

        //3  找不到用户

        User user = userDao.findUserByCode(statecode);
        if(user == null){
            throw new UserException("该用户不存在");
        }else if(user.getState() == 1){
            throw new UserException("该用户已经激活");
        }else if(System.currentTimeMillis() - user.getRegtime().getTime() > 1000L*3600 ){
            //过期
            userDao.deleteUserByCode(statecode);
            throw new UserException("激活邮件已经失效!请重新注册");
        }else{
            userDao.updateUserByCode(statecode);
        }
    }

    public User finUserByNameAndPsd(String username, String password) {
        return userDao.findUserByNameAndPsd(username,password);
    }
}
